<template>
  <section class="upload-page">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        视频上传
      </div>
      <div class="text item">
        <el-button type="primary" @click="uploadFile('video')">视频上传</el-button>
        <el-input type="text" v-model="videoUrl" class="mg-t12"></el-input>
        <a target="_blank" :href="defaultDomain + successedVideoUrl" class="mg-t12">
          视频地址：{{ defaultDomain + successedVideoUrl }}
        </a>
      </div>
    </el-card>

    <el-card class="box-card mg-t12">
      <div slot="header" class="clearfix">
        图片上传{element}
      </div>
      <div class="text item">
        <el-upload
          class="upload"
          :action="imageApi"
          :data="{
            type: 'image',
            scenes: 'oa'
          }"
          :show-file-list="false"
          :on-success="elUploadSuccess"
          :before-upload="beforeElUpload"
        >
          <el-button class="upload-button" type="primary">点击上传</el-button>
        </el-upload>
        <el-input type="text" v-model="imgUrl" class="mg-t12"></el-input>
      </div>
    </el-card>

    <el-card class="box-card mg-t12">
      <div slot="header" class="clearfix">
        图片上传{DIY base64}
      </div>
      <div class="text item">
        <el-button class="upload-button" type="primary" @click="uploadFile('image')">点击上传</el-button>
        <el-input type="text" v-model="imgUrl" class="mg-t12"></el-input>
        <a target="_blank" :href="defaultDomain + successedImgUrl" class="mg-t12">
          图片地址：{{ defaultDomain + successedImgUrl }}
        </a>
      </div>
    </el-card>
  </section>
</template>
<script>
import Axios from 'axios'
import { isVideo, isImage } from '@utils/type-judge'
import compressImgToBase64 from '@utils/compress-img'
export default {
  name: 'Upload',
  data () {
    const PRODUCTION = false
    return {
      videoApi: '//static.tiqianle.com/upload?scenes=salesvideo&type=file&output_type=json', // lx sales视频上传地址
      imageApi: '//static.tiqianle.com/upload4base64',
      videoUrl: '',
      imgUrl: '',
      defaultDomain: PRODUCTION === true ? '//img1.fenqile.com' : '//cimg1.fenqile.com', // lx静态资源域名
      successedVideoUrl: '/salesvideo2/M00/ex/20211112174759-b4f3e60a-866c-4d6a-85dc-7bee6129d258.mp4',
      successedImgUrl: '/oa6/M00/ex/20211115094805-bb775773-5196-4625-b8f4-10edecf2f684.png'
    }
  },
  methods: {
    uploadFile (type) { // type [image, video]
      const input = document.createElement('input')
      input.setAttribute('type', 'file')
      input.click()
      input.onchange = e => {
        const file = e.target.files[0]
        if (file) {
          if (type === 'video') {
            if (!isVideo(file.name)) { this.$message.error('请选择视频文件'); return }
            this.uploadVideo(file)
          }
          if (type === 'image') {
            if (!isImage(file.name)) { this.$message.error('请选择图片文件'); return }
            this.convert2Base64(file)
          }
        }
      }
    },
    uploadVideo (file) {
      const params = new FormData()
      params.append('file', file)
      try {
        const uploading = this.$loading()
        Axios.create({
          withCredentials: true,
          timeout: 30000,
          'Content-Type': 'multipart/form-data;charset=utf-8'
        }).post(this.videoApi, params).then(res => { // 没有用到DevServe proxy，不区分环境【线上线下只区分域名，上传不用代理】
          uploading.close()
          // 视频上传成功
          const data = res.data
          const url = data.src
          if (url) {
            this.videoUrl = `${this.defaultDomain}${url}`
            this.$message.success('视频上传成功')
          } else {
            this.$message.error('视频上传失败')
          }
        }, () => {
          uploading.close()
          this.$message.info('视频上传失败')
        })
      } catch (e) {
        console.log(e)
      }
    },
    convert2Base64 (file) {
      const dpr = 3
      const maxWidth = 375 * dpr
      const maxheight = 667 * dpr
      compressImgToBase64(file, maxWidth, maxheight).then(data => {
        const base64 = data.split('base64,')[1]
        this.uploadImg({ data: base64 })
      }).catch(e => {
        console.log(e)
        this.$message.error('图片转换失败')
      })
    },
    // 图片上传 【手动上传可用 base64】
    uploadImg (obj) {
      const params = {
        files: [obj.data],
        type: 'image',
        scenes: 'oa'
      }
      const uploading = this.$loading()
      Axios.create({
        timeout: 30000,
        'Content-Type': 'x-www-form-urlencoded;charset=utf-8'
      }).post(this.imageApi, params).then(res => {
        uploading.close()
        const data = res.data
        const url = data.src
        if (url) {
          this.$message.success('图片上传成功')
          this.imgUrl = `${this.defaultDomain}${url}`
        } else {
          this.$message.error('图片上传失败')
        }
      }, err => {
        console.log(err)
      })
    },
    beforeElUpload (file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png')
      const isLt500KB = file.size < (500 * 1024)
      if (!isJPG) {
        this.$message.error('上传图片只能是 jpg/png 格式!')
      }
      if (!isLt500KB) {
        this.$message.error('上传图片大小不能超过 500kb!')
      }
      return isJPG && isLt500KB
    },
    elUploadSuccess (res) {
      console.log('elUploadSuccess: ', res)
      this.imgUrl = res.domain + res.src
    }
  }
}
</script>
<style lang="less" scoped>

</style>
